<template>
    <div id="body-padding">
        <p id="p">更换头像</p>
        <div id="img">

            <img :src="'http://localhost:3000'+(img?img:'/img/avatar/mr.jpg')" alt="">
        </div>
        <div id="av">
            <label for="avatar" id="lab" ref="labelAvatar"><span>+</span><p>点击选择</p></label>
            <input 
                type="file" 
                style="display:none" 
                id="avatar"
                @change="fileChange"
                accept="image/jpeg,image/png,image/gif"
            >
            <br>
            <button :disabled="!file.name" @click="btnClick">更换头像</button>
        </div>
        
        
    </div>
</template>

<script>

export default {
    data(){
        return{
            img:"",
            file:{}
        }
    },
    methods:{
        fileChange(e){
            if(!e.target.files[0]){
                return;
            };
            this.file = e.target.files[0];
            var url = URL.createObjectURL(e.target.files[0]);
            this.$refs.labelAvatar.style["background-image"]="url("+url+")";
            this.$refs.labelAvatar.textContent = "";
        },
        btnClick(){
            // console.log(this.file)
            this.$store.dispatch("avatarimg",this.file)
        },
        mount(){
            this.http.get("/users/setting")
            .then(res=>{
                if(res.data.err==5){
                    this.layer.msg("请先登录");
                    window.location.href = "http://localhost:8080/#/login";
                }
                if(res.data.err==0){
                    this.img = res.data.data.avatar;
                }
            })
        },
    },
    activated(){
        this.mount();
        this.$store.dispatch("word");
    },
}
</script>

<style scoped>
#img img{
    width: 64px;
    height: 64px;
    border-radius: 50%;
    position: absolute;
    right: 50px;
    top: 50px;
}
#av{
    text-align: center;
    margin-top: 120px;
}
#lab{
    display: inline-block;
    border: solid 1px #333;
    width: 200px;
    height: 200px;
    background-size: 100% 100%;
}
#lab span{
    line-height: 170px;
    font-size: 150px;
}
#lab p{
    margin: 0;
}
button{
    margin-top: 40px;
    width: 100px;
    height: 40px;
    border-radius: 4px;
    border: solid 1px #317EF3;
    background-color: #317EF3;
    color: white;
}
button:disabled{
    border: solid 1px #999;
    background-color: #999;
    color: #333;
}
</style>